<?php

namespace app\api\home;

use think\Cache;
use think\Validate;

class Sms extends Base
{
    public function send()
    {
        if (!$this->checkReferer()) {
            return $this->apiReturn('非法请求', 1);
        }
        if (!request()->isPost()) {
            return $this->apiReturn('方法不存在', 1);
        }
        $tel = input('param.tel/d');
        //防csrf
        /*if (!$this->checkCsrf()) {
            return $this->apiReturn('非法请求', 1);
        }*/
        if (!is_mobile($tel)) {
            return $this->apiReturn('手机号不正确', 1);
        }
        $verifyCode = input('post.verifyCode');
        if (!captcha_check($verifyCode)) {
            // 校验失败
            return $this->apiReturn('图形验证码错误请重新输入', 2);
        }
        $cacheKey = sprintf(config('login_sms_code_key'), $tel);
        $cacheCode = cache($cacheKey);
        if (!empty($cacheCode)) {
            // 如果缓存中存在信息, 判断时间差在120秒之内的不允许发送
            if (floor(time() - intval($cacheCode['time'])) <= config('send_sms_code_time_interval')) {
                return $this->apiReturn('60秒内只允许发送一条短信', 1);
            }
        }
        $code = random(6);
        $time = time();
        try {
            runhook('send_sms', ['tel' => $tel, 'data' => ['code' => $code], 'templatecode' => 'SMS_152549443']);
            $cacheData = [
                'tel' => $tel,
                'code' => $code,
                'time' => $time,
            ];
            cache($cacheKey, $cacheData, 300);

            return $this->apiReturn('发送成功');
        } catch (\Exception $e) {
            trace('短信平台调用异常:'.$e->getMessage(), 'error');

            return $this->apiReturn('发送短信失败', 1);
        }
    }

    private function checkCsrf()
    {
        $tel = input('param.tel/d');
        $validate = new Validate([
            'tel' => 'require|max:11|token',
        ]);
        $data = [
            'tel' => $tel,
            '__token__' => input('param.__token__'),
        ];

        return $validate->check($data);
    }
}
